package com.beiding.controller;

import com.beiding.pojo.Group;
import com.beiding.pojo.StaticResource;
import com.beiding.service.StaticResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.List;

@RestController
public class ResourceRest {

    private StaticResourceService resourceService;

    @Autowired
    public void setResourceService(StaticResourceService resourceService) {
        this.resourceService = resourceService;
    }

    //上传资源(多文件上传)
    //@CrossOrigin(origins = "https://www.beiding.club")
    @PostMapping(value = "/singleUpload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE, headers = "content-type=multipart/form-data")
    String singleUpload(@RequestPart MultipartFile file){

        List<String> list = resourceService.saveResourceGroup(Group.create(new MultipartFile[]{file}));

        return list.size() == 0 ? null : list.get(0);

    }

    //上传资源(多文件上传)
    //@CrossOrigin(origins = "https://www.beiding.club")
    @PostMapping(value = "/multiUpload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE, headers = "content-type=multipart/form-data")
    List<String> multiUpload(@RequestPart MultipartFile[] file){

        return file.length == 0 ? null : resourceService.saveResourceGroup(Group.create(file));
    }

    //下载资源(下载源文件)
    //@CrossOrigin(origins = "https://www.beiding.club")
    @GetMapping("/get/{resourceId}")
    ResponseEntity<Resource> get(@PathVariable String resourceId) throws IOException {

        StaticResource resource = resourceService.get(resourceId, "id", "fileName");

        if (resource == null) {
            return ResponseEntity.notFound().build();
        }

        FileSystemResource systemResource = new FileSystemResource(resource.absolutePathFile());
        if (!systemResource.exists()) {
            return ResponseEntity.notFound().build();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(ContentDisposition
                .builder("attachment")
                .size(systemResource.contentLength())
                .filename(resource.getFileName())
                .build());

        return ResponseEntity.ok()
                .headers(headers)
                .body(systemResource);
    }


    //预览资源
    //@CrossOrigin(origins = "https://www.beiding.club")


    /**
     * @param rank 缩略等级.从1到5,逐步递减
     */
    @GetMapping("/preview/{rank}/{resourceId}.jpg")
    ResponseEntity<Resource> preview(@PathVariable String resourceId, @PathVariable int rank) throws IOException {

        if (rank < 1 || rank > 5) {
            return ResponseEntity.notFound().build();
        }

        StaticResource resource = resourceService.get(resourceId, "id", "fileName");

        if (resource == null) {
            return ResponseEntity.notFound().build();
        }

        File file = new File(resource.absolutePathFile().getAbsolutePath() + "-" + rank);
        FileSystemResource systemResource = new FileSystemResource(file);

        if (!systemResource.exists()) {
            return ResponseEntity.notFound().build();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(ContentDisposition
                .builder("inline")
                .size(systemResource.contentLength())
                .filename(resource.getFileName())
                .build());

        headers.setContentType(MediaType.IMAGE_JPEG);

        return ResponseEntity.ok()
                .headers(headers)
                .body(systemResource);
    }


    //认领
    @PostMapping("/claim")
    List<String> claim(Principal principal,@RequestParam List<String> resourceIds){
        //认领资源,必须指明资源持有者

        System.out.println("发起认领操作");

        return resourceService.claim(principal,resourceIds);
    }

    //移除资源
    @PostMapping("/remove")
    List<String> remove(Principal principal,@RequestParam String[] resourceIds) {
        return resourceService.remove(principal, resourceIds);
    }

}
